package com.baliejun.springsell.service.impl;


import com.baliejun.springsell.bean.ProductInfo;
import com.baliejun.springsell.dao.ProductInfoDao;
import com.baliejun.springsell.dto.OrderCartDTO;
import com.baliejun.springsell.enums.ResultEnum;
import com.baliejun.springsell.exception.SellException;
import com.baliejun.springsell.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @Author: LiejunBa
 * @Description:
 * @Date: 2020/12/2 3:41 下午
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {

    @Autowired
    private ProductInfoDao dao;

    @Override
    public ProductInfo findOne(String productId) {
        return dao.findById(productId).orElse(null);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        List<ProductInfo> productInfoList = dao.findByProductStatus(0);
        return productInfoList;
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return dao.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return dao.save(productInfo);
    }



    @Override
    @Transactional
    public void increaseStock(List<OrderCartDTO> orderCartDTOList) {

        for (OrderCartDTO orderCartDTO : orderCartDTOList){
            //查询商品信息，通过productId
            ProductInfo productInfo = findOne(orderCartDTO.getProductId());
            //商品不存在
            if (productInfo == null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //增加库存
            Integer result = productInfo.getProductStock() + orderCartDTO.getProductQuantity();
            productInfo.setProductStock(result);

            //更新到数据库
            save(productInfo);

        }


    }


    @Override
    @Transactional
    public void decreaseStock(List<OrderCartDTO> orderCartDTOList) {
        for (OrderCartDTO orderCartDTO : orderCartDTOList){
            //查询商品信息
            ProductInfo productInfo = findOne(orderCartDTO.getProductId());
            //商品不存在
            if (productInfo == null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //商品存在，判断库存数据
            Integer result =  productInfo.getProductStock() - orderCartDTO.getProductQuantity();
            if (result < 0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            //把减掉的结果，存入到库存中
            productInfo.setProductStock(result);
            save(productInfo);
        }
    }
}
